//购物车数组
//数组元素格式：{product:{},num:1}
let shopArray = [];

function $(id){
    return document.getElementById(id);
}

window.onload = function (){
    showBook(bookArray);
}

/**
 * 显示书籍信息
 * @param array 书籍数组
 */
function showBook(array){
    var str = "";
    array.forEach(n => {
        str += `<tr><td>${n.name}</td><td>${n.auth}</td><td>${n.price}</td>
            <td><input type="button" value="查看" onclick="findByCode(${n.code})">
            <input type="button" value="加入购物车" onclick="addShop(${n.code})"></td></tr>`;
    });
    $("bookData").innerHTML = str;
}

/**
 * 按编号显示书籍信息
 * @param code 书籍编号
 */
function findByCode(code){
    //按编号查询书籍对象
    var bookObj = bookArray.find(n => n.code == code);
    $("nameSpan").innerHTML = bookObj.name;
    $("authSpan").innerHTML = bookObj.auth;
    $("priceSpan").innerHTML = bookObj.price;
    $("publishingSpan").innerHTML = bookObj.publishing;
    $("bookImg").src = bookObj.imgPath;
}

/**
 *  按书名查询书籍
 */
function findByName(){
    //查询符合条件的书籍
   var newArray =  bookArray.filter(n => n.name.indexOf($("searchTxt").value) != -1);
   showBook(newArray);
}

/**
 * 购买商品
 * @param buyCode 购买商品编号
 */
function addShop(buyCode){
    $("shopDiv").style.visibility = "visible";
    //查询指定编号对应商品
    var shopObj = shopArray.find(n => n.product.code == buyCode);

    if(shopObj == null){//购物车中不存在该商品
        //从书籍数组中查询指定书籍
        var bookObj = bookArray.find(n => n.code == buyCode);
        //创建购物车对象，购买商品默认为1
        shopObj = {product:bookObj,num:1};
        //将购物信息加入数组
        shopArray.push(shopObj);
    }
    else{//购物车中存在该商品
        shopObj.num += 1;
    }
    showShopInfo();
}

/**
 * 显示购物信息
 */
function showShopInfo(){
    var str = "";
    var total  = 0;
    shopArray.forEach(n => {
       str += `<tr><td>${n.product.name}</td><td>${n.product.price}</td>
        <td><input type="number" min="1" value="${n.num}" onblur="updateNum(${n.product.code} ,this)"></td>
        <td>${n.product.price * n.num}</td>
        <td><input type="button" value="移除商品" onclick="del(${n.product.code})"></td></tr>`;
        total += n.product.price * n.num;
    });
    $("shopData").innerHTML = str;
    $("totalSpan").innerHTML = total;
}

/**
 * 从购物车中移除商品
 * @param code 购买商品编号
 */
function del(code){
    var index = shopArray.findIndex(n => n.product.code == code);
    shopArray.splice(index,1);
    showShopInfo();
}

/**
 * 继续购物
 */
function continueBuy(){
    $("shopDiv").style.visibility = "hidden";
}

/**
 * 修改商品购买数量
 * @param code 购买商品编号
 * @param txtObj 数量文本框
 */
function updateNum(code,txtObj){
    //查询要修改数量的购物车对象
    var shopObj = shopArray.find(n => n.product.code == code);
    shopObj.num = txtObj.value;
    showShopInfo();
}